package com.example.studyenglish.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.studyenglish.R;
import com.example.studyenglish.database.DataAccess;
import com.example.studyenglish.database.SqlHelper;
import com.example.studyenglish.operation.BookOperate;
import com.example.studyenglish.pattern.BookList;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

public class BookSelect extends Activity {

	public static String SETTING_BOOKID = "bookID";
	public static String BOOKNAME = "BOOKNAME";
	public static final int MENU_SETTING = 1;
	public static final int MENU_ABOUT = MENU_SETTING + 1;
	public static final int MENU_CONTACT = MENU_SETTING + 2;
	View myView;

	private Spinner bookselect;
	private TextView textview;

	AlertDialog menuDialog;// menu菜单Dialog
	GridView menuGrid, bottomGrid;
	View menuView;

	/*-- MENU菜单选项下标 --*/
	private final int MENU_REFRESH = 0;// 刷新
	private final int MENU_QUIT = 1;// 退出
	private final int MENU_IMPORT = 2;// 倒入新词库
	private final int MENU_HELP = 3;// 帮助
	private final int MENU_ABOUT1 = 4;// 关于
	private final int MENU_DELETE = 5;// 删除词库

	/*-- 底部菜单选项下标--*/
	private final int BOTTOM_HOME = 0;// 首页
	private final int BOTTOM_BACK = 1;// 退后
	private final int BOTTOM_FORWARD = 2;// 前进
	private final int BOTTOM_RUSTY = 3;// 生词
	private final int BOTTOM_MENU = 4;// 菜单

	/** 底部菜单图片 **/
	int[] bottom_image = { R.drawable.bottom_home, R.drawable.bottom_back,
			R.drawable.bottom_forward, R.drawable.bottom_rusty,
			R.drawable.bottom_menu };
	/** 底部菜单文字 **/
	String[] bottom_name = { "首页", "后退", "前进", "生词", "菜单" };

	/** GRIDVIEW菜单图片 **/
	int[] menu_grid_image = { R.drawable.menu_refresh, R.drawable.menu_quit,
			R.drawable.menu_import, R.drawable.menu_help,
			R.drawable.menu_about, R.drawable.menu_delete };
	/** GRIDVIEW菜单文字 **/
	String[] menu_grid_name = { "刷新", "退出", "新词库", "帮助", "关于", "删词库" };

	/**
	 * @jason
	 */

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bookselect);

		// 创建底部菜单
		bottomGrid = (GridView) findViewById(R.id.GridView_Bottom2);
		bottomGrid.setBackgroundResource(R.drawable.bottom_background);// 设置背景
		bottomGrid.setNumColumns(5);// 设置每行列数
		bottomGrid.setGravity(Gravity.CENTER);// 位置居中
		bottomGrid.setVerticalSpacing(10);// 垂直间隔
		bottomGrid.setHorizontalSpacing(10);// 水平间隔
		bottomGrid.setAdapter(getMenuAdapter(bottom_name, bottom_image));// 设置菜单Adapter

		// 监听底部菜单选项
		bottomGrid.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
				switch (arg2) {
					case BOTTOM_HOME: {
						Intent i = new Intent(BookSelect.this, Main.class);
						startActivity(i);
						break;
					}

					case BOTTOM_BACK: {
						Intent i = new Intent(BookSelect.this, Main.class);
						startActivity(i);
						break;
					}
					case BOTTOM_FORWARD:
					{ Intent i=new
                            Intent(BookSelect.this,Learning
							.class); startActivity(i); break;}


					case BOTTOM_RUSTY:
					{ Intent i=new
                            Intent(BookSelect.this,Rusty.class);
						startActivity(i); break;}

					case BOTTOM_MENU:
						menuDialog.show();
						break;
				}
			}
		});

		// 自定义menu菜单
		menuView = View.inflate(this, R.layout.main_bottom_menu, null);

		// 创建AlertDialog
		menuDialog = new AlertDialog.Builder(this).create();
		menuDialog.setView(menuView);
		menuDialog.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode,
                                 KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_MENU)// 监听按键bottom_menu
				{
					dialog.dismiss(); // 弹出对话窗口
				}
				return false;
			}
		});

		menuGrid = (GridView) menuView.findViewById(R.id.gridview);
		menuGrid.setAdapter(getMenuAdapter(menu_grid_name, menu_grid_image));

		// 监听menuGrid选项
		menuGrid.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
				switch (arg2) {
					case MENU_REFRESH:// 刷新重置词库
					{
						Dialog dialog = new AlertDialog.Builder(BookSelect.this)
								.setTitle("重置当前词库")
								.setMessage("确定要将这个词库重置吗？它将失去所有学习记录")
								.setPositiveButton("确定",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int whichButton) {
												DataAccess data = new DataAccess(
														BookSelect.this);
												data.ResetBook();
												Toast.makeText(BookSelect.this,
														"该词库已被重置",
														Toast.LENGTH_SHORT).show();
											}
										})
								.setNegativeButton("取消",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int whichButton) {
											}
										}).create();
						dialog.show();
						break;
					}
					case MENU_QUIT:// 退出程序
					{
						System.exit(0);
						break;
					}
					case MENU_IMPORT://
					{
						Intent i = new Intent(BookSelect.this, BookImport.class);
						startActivity(i);
						break;
					}
					case MENU_HELP:// 帮助
					{
						Intent i = new Intent(BookSelect.this, MenuHelp.class);
						startActivity(i);
						break;
					}

					case MENU_ABOUT1:// 关于
					{
						Intent i = new Intent(BookSelect.this, MenuAbout.class);
						startActivity(i);
						break;
					}
					case MENU_DELETE: {
						Dialog dialog = new AlertDialog.Builder(BookSelect.this)
								.setTitle("删除当前词库")
								.setMessage("确定要将这个词库删除吗？")
								.setPositiveButton("确定",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int whichButton) {
												DataAccess data = new DataAccess(
														BookSelect.this);
												data.DeleteBook();
												DataAccess.bookID = "";
												Toast.makeText(BookSelect.this, "该词库已删除",
														Toast.LENGTH_SHORT).show();
											}
										})
								.setNegativeButton("取消",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int whichButton) {
											}
										}).create();
						dialog.show();
					}

				}
			}
		});

		textview = (TextView) findViewById(R.id.bookdetails);
		bookselect = (Spinner) findViewById(R.id.bookselect);

		BookOperate bookoperate = new BookOperate();
		SharedPreferences setting = getSharedPreferences(
				"com.example.studyenglish_preferences", MODE_PRIVATE);
		bookoperate.setNotify(setting.getString("time", "18:00 下午"),
				BookSelect.this);

		File dir = new File("data/data/com.example.studyenglish/databases");
		if (!dir.exists()) {
			dir.mkdir();
		}
		if (!(new File(SqlHelper.DB_NAME)).exists()) {

			FileOutputStream fos;
			try {
				fos = new FileOutputStream(SqlHelper.DB_NAME);

				byte[] buffer = new byte[8192];
				int count = 0;
				InputStream is = getResources().openRawResource(R.raw.challenge);
				while ((count = is.read(buffer)) > 0) {
					fos.write(buffer, 0, count);
				}

				fos.close();
				is.close();
			} catch (Exception e) {
				// TODO Auto-generatecetd catch block
				e.printStackTrace();
			}
		}

		SharedPreferences settings = getSharedPreferences(SETTING_BOOKID, 0);
		DataAccess.bookID = settings.getString(BOOKNAME, "");
		bookoperate.UpdateListInfo(BookSelect.this);
		initSpinner();

	}

	private void initSpinner() {
		DataAccess data = new DataAccess(this);
		final ArrayList<BookList> bookList = data.QueryBook(null, null);
		// Log.i("size", String.valueOf(bookList.size()));
		String[] books = new String[bookList.size()];
		int i = 0;
		for (; i < bookList.size(); i++) {
			books[i] = bookList.get(i).getName();
		}

		ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(
				this, android.R.layout.simple_spinner_item, books);

		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		bookselect.setAdapter(adapter);
		bookselect.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
				DataAccess.bookID = bookList.get(arg2).getID();
				textview.setText("\n        您将学习:\n" + "        "
						+ bookList.get(arg2).getName() + "\n"
						+ "\n        该词库总词汇量:\n" + "        "
						+ bookList.get(arg2).getNumOfWord() + "(个)");
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});
	}

	private SimpleAdapter getMenuAdapter(String[] menuNameArray,
                                         int[] imageResourceArray) {
		ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
		for (int i = 0; i < menuNameArray.length; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("itemImage", imageResourceArray[i]);
			map.put("itemText", menuNameArray[i]);
			data.add(map);
		}
		SimpleAdapter simperAdapter = new SimpleAdapter(this, data,
				R.layout.main_item_menu,
				new String[] { "itemImage", "itemText" }, new int[] {
				R.id.item_image, R.id.item_text });
		return simperAdapter;
	}

}
